<?php

namespace app\admin\controller\tuan;

use app\admin\model\Card;
use app\admin\model\City;
use app\admin\model\Consume;
use app\admin\model\TuanCode;
use app\admin\model\User;
use app\common\controller\Backend;

use think\Controller;
use think\Db;
use think\Request;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Accountstatistics extends Backend
{
    
    /**
     * TuanOrder模型对象
     */
    protected $model = null;
    protected $order_type;
    protected $pay_type;
//    protected $searchFields = 'shop.shop_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->order_type = [
            '1'=>'团购',
            '2'=>'买单',
            '3'=>'充值',
        ];
        $this->pay_type = [
            '0'=>'未支付',
            '1'=>'余额支付',
            '2'=>'支付宝',
            '3'=>'微信支付',
        ];

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        $this->loadlang('tuan/accountstatistics');
        $this->loadlang('tuan/billing');
        return $this->view->fetch();
    }

    /**
     * 查看入账列表
     * @date 2017/12/08
     * @author yanggang
     */
    public function table1()
    {
        $this->model = model('TuanOrder');
        $this->searchFields='shop.shop_name';
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $field = 'order_id,order_num,order_type,price,pay_type,update_time,create_time,pay_time,delete,integral,refund_num,num';
            $map = [
                'pay_type'      =>  ['in','2,3'], //只显示第三方交易
                'pay_status'    =>  ['in',[2,-1,-2]],
            ];
            $total = $this->model
                    ->field($field)
                    ->with(['shop','user'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->field($field)
                    ->with([
                        'shop'=>function($query){
                            $query->withField('shop_name');
                        },
                        'user'=>function($query){
                            $query->withField('phone');
                        }
                    ])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $order_type = $this->order_type;
            $pay_type = $this->pay_type;

            foreach ($list as $key=>$value){
                if($value['order_type'] == 3){
                    $list[$key]['shop']['shop_name'] = '团利网';
                }
                $list[$key]['order_type'] = $order_type[$value['order_type']];
                $list[$key]['pay_type'] = $pay_type[$value['pay_type']];
                $list[$key]['price'] = price_format($value['price']);
                $list[$key]['integral'] = '￥ '.number_format($value['integral'],2,'.','');
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    /**
     * 入账详情
     * @date 2017/12/08
     * @atuhor yanggang
     */
    public function edit($ids = NULL)
    {
        $this->model = model('TuanOrder');

        $where = [
            'order_id' => $ids
        ];
        $row = $this->model
            ->with([
                'shop'=>function($query){
                    $query->withField('shop_name,rate,user_id,province_id,city_id,area_id');
                },
                'user'=>function($query){
                    $query->withField('account,nickname,phone');
                },
                'selearnings'
            ])
            ->where($where)
            ->find();

        $selearnings_fee = 0;
        if($row['selearnings']){//计算实际分润
            foreach ($row['selearnings'] as $value){
                $selearnings_ids[]= $value['selearningsID'];
            }
            $selearnings_fee = Db::name('attract')->where(['source'=>['in',$selearnings_ids]])->sum('fees');
            $selearnings_fee = number_format($selearnings_fee,2,'.','');

        }

        //查找商家的会员信息，商家的地区
        $user_id = $row['shop']['user_id'];
        $shop_user_info = (new User())->field('phone,account')->where(['userID'=>$user_id])->find();
        $province = $row['shop']['province_id'];
        $city = $row['shop']['city_id'];
        $area = $row['shop']['area_id'];
        $city_map = [
            'cityID'=>['in',$province.','.$city.','.$area]
        ];
        $local_name = (new City())->where($city_map)->column('name');
        $local_name = implode('-',$local_name);
        //计算当前税率
        //积分秒杀的单直接取店铺的rate
        if($row['tuan_type'] == 2){
            $row['rate'] = $row['shop']['rate'];
        }else{
            $row['rate'] = number_format(($row['price'] - $row['back_money'] - $row['settlement_price'])/$row['price'],2)*100;
        }

        $order_type = $this->order_type;
        $pay_type = $this->pay_type;
        $row['order_type_text'] = $order_type[$row['order_type']];
        if($row['order_type'] == 1){//团购
            $tuan_type = $row->tuan->getAttr('type');
            $row['order_type_text'] = $tuan_type == 1 ? '团购套餐' : '代金券';
            //如果退了券
            if($row['refund_num']  && $row['refund_num'] < $row['num'] ){
                $row['price'] = $row['price'] - $row['price'] * $row['refund_num'] /$row['num'];
                $row['total_price'] = $row['total_price'] - $row['total_price'] * $row['refund_num']/$row['num'];
            }
            //查询消费时间
            $used_time = (new TuanCode())->where(['order_id'=>$ids,'is_used'=>1])->max('used_time');
            $row['update_time'] = $used_time;
        }elseif ($row['order_type'] == 2){//买单
            $row['order_type_text'] = $row['total_price'] == $row['price'] ? '买单':'优惠买单';
        }
        $row['pay_type_text'] = $pay_type[$row['pay_type']];
        $row['shop']['local_name'] = $local_name;
        $row['shop']['user_info'] = $shop_user_info;
        $row['add_integral'] =  $row['order_status'] == 3 ? '+ '.intval($row['price']/100) : '未评价';

        $row['coupon_price'] = price_format($row['total_price']-$row['integral']*100 - $row['price']);
        if($row['discount'] == 0 ){
            $row['discount'] = 10;
        }
        $discount_price = $row['total_price'] * (1- $row['discount']/10);
        $row['discount_text'] = $row['discount'].'折';
        $row['discount'] = price_format($discount_price);
        $row['price'] = price_format($row['price']);
        $row['total_price'] = price_format($row['total_price']);
        $row['settlement_price'] = price_format($row['settlement_price']);
        $row['selearnings_fee'] = price_format($selearnings_fee);
        if($row['integral'] < 1){ //积分小于1的直接显示为0
            $row['integral'] = 0;
        }
        $row['integral'] = '￥ '.number_format($row['integral'],2,'.','');
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 出账列表
     * @date 2017/12/08
     * @author yanggang
     * @return string|\think\response\Json
     */
    public function table2()
    {
        $this->model = model('Consume');
        $this->searchFields = 'fees';
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $total = $this->model
//                ->with([
//                    'user',
//                    'depositlist'
//                ])
//                ->where($where)
//                ->order($sort, $order)
//                ->count();

            $list = $this->model
                ->field('consumeID,ordernum,fees,time,type,id')
                ->with([
                    'user'=>function($query){
                        $query->withField('account,type');
                    },
                    'depositlist'=>function($query){
                        $query->withField('status');
                    }
                ])
                ->where($where)
                ->order($sort, $order)
                ->select();

            foreach ($list as $key=>$value){
                if(!empty($value['depositlist']['status']) && $value['depositlist']['status'] != 3){
                    unset($list[$key]);
                    continue;
                }
            }

            $total = count($list);
            $list = array_slice($list,$offset,$limit);

            foreach ($list as $k=>$v){
                if($v['type'] == 8){
                    $list[$k]['ordernum'] = Db::name('apply_refund')->where('refund_id',$v['id'])->value('refund_number');
                }
                $list[$k]['fees'] = price_format($v['fees']);
                if($v['depositlist']['status']){
                    $list[$k]['type'] = '提现';
                }else{
                    $list[$k]['type'] = '退款';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    /**
     * 出账详情
     * @date 2017/12/08
     * @author yanggang
     * @param null $ids
     * @return string
     */
    public function billing_edit($ids=null)
    {
        $this->model = model('Consume');

        $where = [
            'consume.consumeID' => $ids
        ];
        $row = $this->model
            ->field('consumeID,ordernum,userID,fees,type,time,source,id')
            ->with([
                'user'=>function($query){
                    $query->withField('userID,phone,account,type');
                },
                'property'=>function($query) {
                    $query->where(['property.type' => 1]);
                },
//                'autonym'=>function($query){
//                    $query->where(['autonym.status'=>4]);
//                }
            ])
            ->where($where)
            ->find();

        $user_type = $row->user->getData('type');
        $row['user']['type_text'] = $user_type == 2 ? '商家版' :'会员版';
        $row['fees'] = price_format($row['fees']);
        //提现
        if($row['type'] == 2){
            $depositlist = Db::name('depositlist')->where('consumeID',$row['consumeID'])->find();
            //银行卡信息
            $card_map = [
                'cardID'=>$depositlist['cardID']
            ];
            $card_info = (new Card())->where($card_map)->find();
            $row['card_info'] = $card_info;

            //用户余额
            $row['property']['value'] = price_format($row['property']['value']);

            //实名认证信息
            $autonym = Db::name('autonym')->where('userID',$row['userID'])->where('status',4)->find();
            $row['autonym'] = $autonym;

            //查询审核人的条件
            $admin_map = [
                'admin_id' => $row['depositlist']['id']
            ];

        //退款
        }else{
            $refund = Db::name('apply_refund')->where('refund_id',$row['id'])->find();
            $row['refund'] = $refund;

            //查询审核人的条件
            $admin_map = [
                'admin_id'  =>  $refund['admin_id']
            ];
        }

        //审核人
        $admin_name = Db::name('admin')->where($admin_map)->value('user_name');
        $row['admin_name'] = $admin_name;

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
